package org.groupg.practice;

import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;

public class AppendToCsv {
    public static void main(String[] args) {
        String filePath = "existing_data.csv";

        try {
            // 如果文件不存在，先创建并写入标题
            if (!Files.exists(Paths.get(filePath))) {
                try (Writer writer = Files.newBufferedWriter(Paths.get(filePath))) {
                    CSVWriter csvWriter = new CSVWriter(writer);
                    csvWriter.writeNext(new String[]{"ID", "Value", "Category"});
                }
            }

            // 以追加模式打开文件
            try (Writer writer = Files.newBufferedWriter(
                    Paths.get(filePath),
                    StandardOpenOption.APPEND);
                 CSVWriter csvWriter = new CSVWriter(writer)) {

                // 追加新数据
                csvWriter.writeNext(new String[]{"A100", "23.75", "Electronics"});
                csvWriter.writeNext(new String[]{"A101", "42.99", "Books"});
                csvWriter.writeNext(new String[]{"A102", "15.49", "Home"});

                System.out.println("数据已追加到CSV文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}